define(['app'], function(app) {
	'use strict';

	var controller = function controller($scope, Activitythree, $ionicSlideBoxDelegate, GoPage, GoDialog, GoShare,GoWapAuth, $window, $timeout, $stateParams, $ionicModal, Auth, $interval, $ionicPopup) {
		
		$scope.input = new Object();
		$scope.isshow = true;
		
		//画面加载
		$scope.$on('$ionicView.afterEnter', function() {
			$scope.set_time = false;
			$scope.goods_id = $stateParams.goods_id;
			$scope.product_id = $stateParams.product_id;
			$scope.act_id = $stateParams.act_id;
			getMethod();
			$scope.init_data();
		}, false);
		
		$scope.$on('$ionicView.afterLeave', function() {
			$scope.closeGuidShare();
		}, false);
		
		$scope.$on('$ionicView.beforeLeave',function(){//取消定时器
			if($scope.timer){
				$interval.cancel($scope.timer);
			}
			if($scope.timerForPrice){
				$interval.cancel($scope.timerForPrice);
			}
		})
		
		
		/*
		 * 9个活动
		 * 活动类型
			1=>团购活动
			2=>秒杀活动
			3=>限时抢购活动
			4=>拍卖活动
			5=>新品测试活动
			6=>新品赠送活动
			7=>新品公告活动
			8=>产品推广活动(直播)
			9=>产品促销活动
		*/
		function getMethod(){
			$scope.isBigWidth = false;
			$scope.activitType = $stateParams.type;//html据此判断按钮的显示
			if($stateParams.type=='1') {
				$scope.title = "疯狂团购";
				$scope.method = "goods.groupbuy.detail";
				$scope.buyMethod = "marketing.groupbuy.checkOut";
				$scope.afsrueType = "groupbuy";
				$scope.buyBtnText = "团一下";
			}
			if($stateParams.type=='2') {
				$scope.title = "限时秒杀";
				$scope.method = "goods.seckill.detail";
				$scope.buyMethod = "marketing.seckill.checkOut";
				$scope.afsrueType = "spike";
				$scope.buyBtnText = "立即秒杀";
				if($window.innerWidth>=375){//如果是大屏幕，则显示原价和中奖价，否则只显示中奖价
					$scope.isBigWidth = true;
				}
			}
			if($stateParams.type=='3') {
				$scope.title = "限时抢购";
				$scope.method = "goods.panicbuy.detail";
				$scope.buyMethod = "marketing.panicbuy.checkOut";
				$scope.afsrueType = "timedbuy";
				$scope.buyBtnText = "立即抢购";
			}
			if($stateParams.type=='4') {
				$scope.title = "限时拍卖";
				$scope.method = "marketing.auction.view";
			}
		}
		
		//初始化页面
		$scope.init_data = function() {
			Activitythree.product_detail($scope.goods_id, $scope.act_id,$scope.product_id,$scope.method, function(data) {
				if(!data.success){
					GoDialog.alert("提示",data.msg,function(){
						GoPage.go_back();
					})
					return;
				}
				console.log(data)
				if(data.result) {
					$scope.input.goods_num = 1;
					$scope.minBuyNum = 1;//购买基数 默认为1
					$scope.startBuyNum = 1;//起购数 默认为1
					
					//起购数
					if((data.result.min_buy != null && data.result.min_buy != '0') || (data.result.minimum != null && data.result.minimum != '0')){
						//基数>起购数时，起购数=基数
						if(data.result.min_buy>data.result.minimum){
							$scope.startBuyNum = parseInt(data.result.min_buy);
						}
						else{
							$scope.startBuyNum = parseInt(data.result.minimum);
						}
						$scope.input.goods_num = $scope.startBuyNum;
					}
					//购买基数
					if(data.result.min_buy != null && data.result.min_buy != '0'){
						$scope.minBuyNum = parseInt(data.result.min_buy);
					}
					if($stateParams.type=='4'){//限时拍卖，字段转换
						$scope.input.goods_num = Number(data.result.start_price_dis);//出价输入框
						$scope.minBuyNum = Number(data.result.amplitude);//加价幅度
						data.result.act_start_time = data.result.start_time;//字段转换
						data.result.act_end_time = data.result.end_time;
						data.result.price = data.result.last_price;//data.result.last_price/start_price
						data.result.title_images = [{id:"",image:data.result.image}];
						data.result.paimaiNum = data.result.act_logs?data.result.act_logs.length:0;//出价次数
						$scope.timerForPrice = $interval(getLastPrice,10000);
					}
					$scope.detail = data.result;
					$scope.init_time(data.result, data.process_time);
					$ionicSlideBoxDelegate.$getByHandle('advs-handle').update(); //解决无法加载
					$ionicSlideBoxDelegate.$getByHandle('advs-handle').loop(true); //循环
					$scope.go_share_wx();
				}
			});
		}
		
		//限时拍卖专用，每隔10秒取一次最新价格和出价记录的
		function getLastPrice(){
			Activitythree.auction_detail($scope.goods_id, $scope.act_id,$scope.product_id, function(data) {
				$scope.detail.price = data.result.last_price;
				$scope.input.goods_num = Number(data.result.start_price_dis);//出价输入框
				$scope.detail.paimaiNum = data.result.act_logs?data.result.act_logs.length:0;//出价次数
			})
		}
		
		
		//跳转到首页
		$scope.onshow_first = function() {
			GoPage.go_states("first", {"store_id": $scope.detail.store_id});
		};
		
		//商品数量+1
		$scope.goods_add = function() {
			if($scope.detail.max_count != undefined)
				var max_count = $scope.detail.max_count > $scope.detail.store ? $scope.detail.store : $scope.detail.max_count;
			else
				var max_count = $scope.detail.store;
			if($scope.input.goods_num>=$scope.detail.store||$scope.input.goods_num >= max_count) {
				GoDialog.alert("提示","最多只能购买"+max_count+"件");
				return;
			}
			$scope.input.goods_num += parseInt($scope.minBuyNum);
		};
		
		//商品数量-1
		$scope.goods_reduce = function() {
			if($scope.input.goods_num > $scope.startBuyNum)
				$scope.input.goods_num -= parseInt($scope.startBuyNum);
		};
		
		/************提交表单***************/
		//限时秒杀、限时抢购
		$scope.submit = function() {
			if($scope.detail.store<1) {
				GoDialog.alert("提示","对不起，该商品没有库存了！");
				return;
			}
			var type = 'timebuy';//限时抢购
			var product = new Array();
			var adjunct = new Array();
			if(type != 'coupon' && type != 'package') {
				var i = product.length;
				product[i] = {
					"product_id": $scope.product_id,
				}
			}
			if(!$scope.input.goods_num) {
				GoDialog.toast("请填写购买数量");
				return;
			}
			Activitythree.buy($scope.detail.goods_id, $scope.product_id, $scope.input.goods_num, $scope.act_id, $scope.buyMethod, function(data) {
				if(data.success)
					GoPage.go_states("afsrue", {
						"type": $scope.afsrueType,
						"status": 'fastbuy'
					});
				else {
					GoDialog.alert("提示",data.msg);
//					$scope.init_data();
				}
			})
		}
		
		//限时拍卖
		$scope.submitPrice =function(){
			if($scope.detail.isOwner=='1'){
				GoDialog.alert('提交','自己店铺的拍品不能出价');
				return;
			}
			if(!$scope.input.checked&&!$scope.detail.is_price){
				$scope.openPopup_BZJrule();
				return;
			}
			Activitythree.auction_apply($scope.act_id,$scope.input.goods_num,function(data){
				if(data.success=="failed"){
					GoDialog.alert("提示",data.msg);
					return;
				}
				if(data.success){//成功，则更新当前价、出价次数、出价输入框
					GoDialog.toast(data.msg);
					$scope.detail.paimaiNum++;
					$scope.detail.price = $scope.input.goods_num;
					$scope.input.goods_num = $scope.input.goods_num + Number($scope.detail.amplitude);
				}
			})
		}
		/************提交表单***************/
		
		$scope.init_time = function(data, now_time) {
			if(now_time < data.act_start_time) {
				$scope.isshow = false;
				$scope.btn_name = '未开始';
				$scope.act_time_name = '距开始';
				if(data.now_time != undefined)
					data.now_time = data.now_time - 1;
				else
					data.now_time = data.act_start_time - now_time;
			} else {
				$scope.act_time_name = '距结束';
				if($scope.detail.store <= 0||!$scope.detail.max_count) {
					$scope.btn_name = '已售罄';
					$scope.isshow = false;
				}
				if(data.now_time != undefined)
					data.now_time = data.now_time - 1;
				else
					data.now_time = data.act_end_time - now_time;
			}
			data.formate_time = $scope.formate_time(data.now_time);
			$scope.set_timer(now_time);
		};
		
		//定时器
		$scope.set_timer = function(now_time) {
			if(!$scope.set_time){
				$scope.set_time = true;
			}else{
				return;
			}
			$scope.timer =  $interval(function() {
				if($scope.detail.now_time != undefined) {
					$scope.detail.now_time = $scope.detail.now_time - 1;
					//判断活动商品是否由即将开始状态转成已开始状态
					if($scope.detail.now_time <= 0) {
						if(now_time >= $scope.detail.act_start_time) {
							$scope.detail.now_time = $scope.detail.act_end_time - now_time;
							$scope.act_time_name = '距结束';
							if($scope.detail.store <= 0) {
								$scope.btn_name = '已售罄';
								$scope.isshow = false;
							} else {
								$scope.isshow = true;
							}
						}
					}
				 }else {
					if(now_time > $scope.detail.act_start_time) {
						$scope.detail.now_time = $scope.detail.act_end_time - now_time;
						$scope.act_time_name = '距结束';
						if($scope.detail.store <= 0) {
							$scope.btn_name = '已售罄';
							$scope.isshow = false;
						} else {
							$scope.isshow = true;
						}
					} else {
						$scope.detail.now_time = $scope.detail.act_start_time - now_time;
						$scope.act_time_name = '距开始';
					}
				}
				now_time++;
				$scope.detail.formate_time = $scope.formate_time($scope.detail.now_time,now_time);
			}, 1000)
		};
		
		//计算时间
		$scope.formate_time = function(time) {
			var timeArr = [0,0,0,0];
			if(time > 0) {
				var day = parseInt(time / (3600 * 24));
				var hour = parseInt((time % (3600 * 24)) / 3600);
				if(hour < 10)
					hour = "0" + hour;
				var min = parseInt((time % 3600) / 60);
				if(min < 10)
					min = "0" + min;
				var second = time % 60;
				if(second < 10)
					second = "0" + second;
//				return day + '天' + hour + '小时' + min + '分' + second + '秒';
				timeArr[0] = day;
				timeArr[1] = hour;
				timeArr[2] = min;
				timeArr[3] = second;
			} else {
				$scope.isshow = false;
				$scope.btn_name = '已结束';
//				return '0天0小时0分0秒';
			}
			return timeArr;
		};
		
		
		//跳转到商品详情
		$scope.onshow_productInfo = function() {
			GoPage.go_states("activity_info", {
				"goods_id": $scope.goods_id,
				"act_id": $scope.act_id,
				"product_id": $scope.product_id,
				"type":$stateParams.type
			});
		}
		
		//上拉跳转到商品详情
		$scope.isLoad = false;
		$scope.doRefreshMore = function(){
			$scope.isLoad = true;
			$scope.$broadcast('scroll.infiniteScrollComplete');
			$timeout(function() {
				$scope.isLoad = false;
			}, 3000);
			$scope.onshow_productInfo();
		}
		
		
		/***********显示《客服》**********/
		$ionicModal.fromTemplateUrl("templates/modal/customer_service.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_customer = modal;
		});
		//打开
		$scope.openModal_customer = function() {//客服
			Activitythree.contact_show($scope.detail.store_id, function(data) {
				if(!data||data.cusphone.length<1){
					GoDialog.alert("提示","店家暂时还没有设置客服哦");
					return;
				}
				$scope.customerList = data;
				$scope.modal_customer.show();
			})
		}
		//隐藏
		$scope.closeModal_customer = function() {
			$scope.modal_customer.hide();
		}
		//选择客服
		$scope.selectCustomer = function(index){
			$scope.customerList_index = index;
		}
		//联系客服
		$scope.do_tel = function() {
			$scope.closeModal_customer();
			if(!$scope.customerList_index) return;
			var param = $scope.customerList.cusphone[$scope.customerList_index];
			if(param.type == 2) {
				$window.location.href = "tel:" + param.value;
			} else if(param.type == 1) {
				if(param.isonline == '0') {
					GoPage.go_txcall3(param.id, param.code, param.vvckey);
				} else {
					GoPage.go_txcall2($scope.detail.store_id, $scope.detail.store_id, param.id, param.code, param.vvckey);
				}
			}
		}
		/***********显示《客服》**********/
		
		/***************活动规则**************/
		$ionicModal.fromTemplateUrl("templates/modal/activityRule.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_rule = modal;
		});
		//打开
		$scope.openModal_rule = function() {
			if(!$scope.detail.rule) {
				GoDialog.alert("提示","暂时没有活动规则哦！");
				return;
			}
			$scope.modal_rule.show();
		}
		//隐藏
		$scope.closeModal_rule = function() {
			$scope.modal_rule.hide();
		}
		/***************活动规则**************/
		
		/***************保证金规则**************/
		var popup_BZJrule;
		$scope.openPopup_BZJrule = function(){
			if($scope.detail.isOwner=='1'){
				GoDialog.alert("提示",'自己店铺的拍品不能出价');
				return;
			}
			popup_BZJrule = $ionicPopup.show({ //show()
				templateUrl: 'templates/modal/auction_apply.html',
				title: "提交保证金",
				isConfirm: true,
				cssClass:"activityThree",
				scope: $scope,
				buttons: [{
					text: "取消",
					onTap: function() {
						
					}	
				},{
					text: "确定",
					type: "buttonOrange",
					onTap: function(e) {
						if(!$scope.input.checked){
							GoDialog.toast("请同意竞拍协议再提交保证金！");
							e.preventDefault();
							return;
						}
						GoPage.go_states('panicauction_pay',{
							'act_id':$scope.act_id,
							'apply_id':$scope.detail.apply_id,
							'goods_id':$scope.goods_id,
							'product_id':$scope.product_id
						});
					}
				}]
			});
		}
		/***************保证金规则**************/
		
		/***************保证金规则里的文章**************/
		$scope.get_article = function(index){
			Activitythree.get_article(index,function(data){
				if(data.success){
//					if(index==101){
			//				$scope.title = '竞拍协议';
			//			}else{
			//				$scope.title = '保证金归属规则'
			//			}
					$scope.article = data.result.content;
					popup_BZJrule.close();//先关闭popup弹窗
					$scope.openModal_article();
				}else{
					GoDialog.alert("提示",data.msg);
				}
			})
		}
		$ionicModal.fromTemplateUrl("templates/modal/auction_article.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_article = modal;
		});
		//打开
		$scope.openModal_article = function() {
			$scope.modal_article.show();
		}
		//隐藏
		$scope.closeModal_article = function() {
			$scope.modal_article.hide();
		}
		/***************保证金规则里的文章**************/
		
		/***************分享**************/
		$ionicModal.fromTemplateUrl("templates/modal/keyshare_modal.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_share = modal;
		});
		//打开
		$scope.openModal_share = function() {
			if($scope.openGuidShare()) {
				$scope.modal_share.show();
			}
		}
		//隐藏
		$scope.closeModal_share = function() {
			$scope.modal_share.hide();
		}
		
		//分享（自定义每个页面的参数）
		$scope.go_share = function(index) {
			var param = new Object();
			if($scope.detail) {
				param.title = $scope.detail.name ? $scope.detail.name : undefined;
				param.desc = $scope.detail.brief ? $scope.detail.brief : undefined;
				param.thumb = $scope.detail.title_images ? $scope.detail.title_images[0].image : undefined;
				param.link = 'activitythree/'+$scope.act_id+'/' +$scope.goods_id+'/'+$scope.product_id;
			}
			GoShare.do_share(param, index);
		}
		
		//分享（自定义每个页面的参数）
		$scope.go_share_wx = function() {
			//分享打开
			GoWapAuth.execisoff(false);
			//设置分享
			var param = new Object();
			if($scope.detail) {
				param.title = $scope.detail.name ? $scope.detail.name : undefined;
				param.desc = $scope.detail.brief ? $scope.detail.brief : undefined;
				param.thumb = $scope.detail.title_images ? $scope.detail.title_images[0].image : undefined;
				param.link = 'activitythree/'+$scope.act_id+'/' +$scope.goods_id+'/'+$scope.product_id;
			}
			GoWapAuth.execshare(param);
		}
		/***************分享**************/
		
		
	}

	controller.$inject = ['$scope', 'Activitythree', '$ionicSlideBoxDelegate', 'GoPage', 'GoDialog', 'GoShare','GoWapAuth', '$window', '$timeout', '$stateParams', '$ionicModal', 'Auth', '$interval','$ionicPopup'];

	return app.registerController("activitythreectrl", controller);
});